package hotgammon.domain;

public class DiceGammamon implements Dice {
    
    private Game game;
    int[] diceValues = null;
    int[] diceValuesLeft = null;
    private int numThrown;
    
    public void setGame(Game game) {
        this.game=game;
    }
    
    public int[] getDiceValues() {
        return this.diceValues;
    }
    
    public int[] thrown() {
        int n1 = (int) (Math.random()*6)+1;
        int n2 = (int) (Math.random()*6)+1;
        return this.setDice(n1,n2);
    }
    
    public int[] setDice(int n1, int n2) {
        if(game.getIsGameStarted()) this.numThrown++;
        int[] lv = this.diceValues;
        
        if (game.getIsGameStarted() && n1==n2) {
            this.diceValues = new int[] {n1,n1,n1,n1};
        } else {
            this.diceValues = new int[] {n1,n2};
        }
        
        if (!game.getIsGameStarted() && lv!=null) {
            if(getDiceSum(lv) > getDiceSum(this.diceValues)) {
                game.setIsRedsTurn(true);
                game.setIsGameStarted(true);
            } else if(getDiceSum(lv) < getDiceSum(this.diceValues))  {
                game.setIsRedsTurn(false);
                game.setIsGameStarted(true);
            }
            int[] tmp = this.diceValues;
            this.diceValues=null;
            return tmp;
        }
        
        return this.diceValues;
    }
    
    public int getNumberOfMovesLeft() {
        int res = 0;
        if (this.diceValues!=null) {
            for (int n : this.diceValues) {
                if (n!=0) res++;
            }
        }
        return res;
    }
    
    public int[] getValuesLeft() {
        return diceValues;
    }
    
    public void setDiceValues(int[] diceValues) {
        this.diceValues = diceValues;
    }
    
    public void setDiceValuesLeft(int[] diceValuesLeft) {
        this.diceValuesLeft = diceValuesLeft;
    }   
    
    public int getNumThrown() {
        return numThrown;
    }
    
    public void setNumThrown(int numThrown) {
        this.numThrown=numThrown;
    }
    
    public int getDiceSum(int[] diceValues) {
        int sum = 0;
        for (int n : diceValues) {
            sum+=n;
        }
        return sum;
    }
}
